package com.ndood.agent.service.user.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ndood.agent.core.constaints.AgentErrCode;
import com.ndood.agent.core.exception.AgentException;
import com.ndood.agent.dao.system.StaffDao;
import com.ndood.agent.pojo.system.StaffPo;
import com.ndood.agent.service.user.AccountPasswordService;

import lombok.extern.slf4j.Slf4j;

/**
 * 密码管理
 */
@Service
@Slf4j
public class AccountPasswordServiceImpl implements AccountPasswordService{

	@Autowired
	private StaffDao staffDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public void changePassword(String userId, String oldPassword, String newPassword) throws AgentException {
	
		log.debug("Setp1: 判断旧密码是否正确");
		StaffPo staff = staffDao.selectByPrimaryKey(Integer.parseInt(userId));
		if(staff == null) {
			throw new AgentException(AgentErrCode.ERR_PASSWORD, "用户不存在");
		}

		log.debug("Step2: 判断旧密码是否匹配");
		boolean matches = passwordEncoder.matches(staff.getPassword(),oldPassword);
		if(!matches) {
			throw new AgentException(AgentErrCode.ERR_PASSWORD, "旧密码错误");
		}
		
		log.debug("Step3: 更新密码");
		staff.setPassword(passwordEncoder.encode(newPassword));
		staff.setUpdateTime(new Date());
		staffDao.updateByPrimaryKeySelective(staff);

	}
	
}
